//
//  LoginVC.swift
//  ImGuider X
//
//  Created by llt on 2018/9/12.
//  Copyright © 2018年 imguider. All rights reserved.
//

import UIKit
import TransitionButton

class LoginVC: BaseVC {
    
    @IBOutlet weak var loginBtn: TransitionButton!
    
    @IBOutlet weak var loginBtnBottom: NSLayoutConstraint!
    
    
    @IBOutlet weak var scanBtn: UIButton!
    @IBOutlet weak var scanLabel: UILabel!
    @IBOutlet weak var countryBtn: UIButton!
    @IBOutlet weak var codeBtn: UIButton!
    
    @IBOutlet weak var phoneNumTF: UITextField!
    @IBOutlet weak var codeTF: UITextField!
    
    @IBOutlet weak var titleLabel: UILabel!
    
    private var timer:Timer?
    
    private let viewmodel = LoginViewModel()
    
    var pageType:Int = 0// 1为绑定手机号
    var bindtripid:String?// 要绑定的行程ID
    
    var needScan: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupData()
    }
    
    deinit {
        
        stopTimer()
    }
    
    private func setupUI() {
        
        loginBtn.setTitle(LocalizedString("login"), for: .normal)
        countryBtn.setTitle(LocalizedString("country_city"), for: .normal)
        codeBtn.setTitle(LocalizedString("get_code"), for: .normal)
        
        scanLabel.text = LocalizedString("scan_login")
        
        phoneNumTF.attributedPlaceholder = NSAttributedString(string: LocalizedString("mobile"), attributes: [NSAttributedString.Key.foregroundColor : UIColor.white.withAlphaComponent(0.5)])
        
        codeTF.attributedPlaceholder = NSAttributedString(string: LocalizedString("code"), attributes: [NSAttributedString.Key.foregroundColor : UIColor.white.withAlphaComponent(0.5)])
        
        setNavBarStyle(.transparency)
        
        if pageType == 1 {
            
            scanBtn.isHidden = true
            loginBtn.setTitle(LocalizedString("bind_mobile"), for: .normal)
            
            let att = NSMutableAttributedString(string: LocalizedString("bind_mobile"))
            att.yy_font = UIFont.boldSystemFont(ofSize: 20)
            att.yy_color = UIColor.white
            self.titleLabel.attributedText = att
            self.loginBtnBottom.constant = 100
        } else {
            
            let att = NSMutableAttributedString(string: LocalizedString("login_slogan"))
            att.yy_font = UIFont.boldSystemFont(ofSize: 20)
            att.yy_color = UIColor.white
            att.yy_lineSpacing = 8
            self.titleLabel.attributedText = att
            
            if ISiPhone4 || ISiPhone5 || ISiPad {
                
                self.titleLabel.numberOfLines = 1
            } else {
                
                self.titleLabel.numberOfLines = 0
            }
        }
        
        viewmodel.pageType = pageType
        
        DispatchQueue.main.after(0.25) {
            
            if self.needScan {
                
                self.loginBtn.startAnimation()
                self.viewmodel.checkTrips()
            }
        }
    }
    
    private func setupData() {
        
        viewmodel.toastText = {
            
            [weak self] errmsg in
            guard let `self` = self, let errmsg = errmsg else { return }
            
            self.view.makeToast(errmsg)
        }
        
        viewmodel.loginSuccess = {
            
            [weak self] success,needScan in
            guard let `self` = self else { return }
            
            if !success {
                
                self.loginBtn.stopAnimation(animationStyle: StopAnimationStyle.shake,revertAfterDelay: 0)
                return
            }
            
            if self.pageType == 1 && needScan {
                
                self.viewmodel.bindTrip(tripid: self.bindtripid!)
                return
            }
            
            self.loginBtn.stopAnimation(animationStyle: self.loginBtn.isEnabled ? .normal :.expand , revertAfterDelay: 0.25, completion: {
                
                if needScan {
                    
                    self.scanpage()
                } else {
                    
                    self.homepage()
                }
            })
            
            
        }
        viewmodel.reloadCountry = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            if let country = self.viewmodel.country {
                
                self.countryBtn.setTitleColor(.white, for: .normal)
                self.countryBtn.setTitle(country.code, for: .normal)
            }
        }
        
        viewmodel.getCodeSuccess = {
            
            [weak self] suc in
            guard let `self` = self else { return }
            
            if !suc {
                
                self.stopTimer()
                self.codeBtn.isEnabled = true
            }
        }
    }
    
    private func startTimer() {
        
        stopTimer()
        
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
    }
    
    private func stopTimer() {
        
        timer?.invalidate()
        timer = nil
    }
    
    @objc private func timerAction() {
        
        let tag = codeBtn.tag - 1
        
        if tag <= 0 {
            
            codeBtn.isEnabled = true
            codeBtn.setTitle(LocalizedString("retry_code"), for: .normal)
            codeBtn.setTitleColor(UIColor.white, for: .normal)
            stopTimer()
        } else {
            
            codeBtn.setTitle("\(tag) s", for: .normal)
            codeBtn.setTitleColor(UIColor.white.withAlphaComponent(0.5), for: .normal)
        }
        
        codeBtn.tag = tag
    }
    
    @IBAction func chooseCountryAction(_ sender: Any) {
        
        let countryVC = SelectCountryVC()
        
        countryVC.complete = {
            
            [weak self] country in
            guard let `self` = self,let country = country else { return }
            
            self.viewmodel.country = country
        }
        
        self.navigationController?.pushViewController(countryVC, animated: true)
    }
    
    @IBAction func getCodeAction(_ sender: UIButton) {
        
        codeBtn.isEnabled = false
        
        codeBtn.tag = 60
        
        startTimer()
        
        viewmodel.getCode(phone: phoneNumTF.text)
    }
    
    @IBAction func loginAction(_ sender: Any) {
        
        loginBtn.startAnimation()
        
        viewmodel.login(phone: phoneNumTF.text, code: codeTF.text)
    }
    
    
    @IBAction func scanCodeAction(_ sender: Any) {
        
        scanpage()
    }
    
    
    private func scanpage() {
        
        let scanVC = ScanVC()
        scanVC.complete = {
            
            [weak self] tripid in
            guard let `self` = self else { return }
            
            if UserManager.share.token?.count ?? 0 > 0 {
                
                self.viewmodel.bindTrip(tripid: tripid)
            } else {
                
                
            }
        }
        
        scanVC.failture = {
            [weak self] in
            guard let `self` = self else { return }
            
            if UserManager.share.token?.count ?? 0 > 0 {
                
                self.loginBtn.stopAnimation(animationStyle: StopAnimationStyle.shake,revertAfterDelay: 0)
            }
            
        }
        
        self.navigationController?.pushViewController(scanVC, animated: true)
    }
    
    private func homepage() {
        
        AppManager.share.HomePage()
        
    }
}

